package com.spring.sunflower.main.fragment;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.tabs.TabLayout;
import com.spring.sunflower.R;
import com.spring.sunflower.base.BaseFragment;
import com.spring.sunflower.main.adapter.TabLayoutSubFragmentAdapter;
import com.spring.sunflower.main.presenter.LivelyPresenter;
import com.spring.sunflower.util.DisplayUtils;
import com.spring.sunflower.util.StatusBarUtil;
import com.spring.sunflower.widget.NoSmoothViewPager;
import com.spring.sunflower.widget.ScaleTransitionPagerTitleView;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.UIUtil;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Kevin on 2021/5/28<br/>
 * <p>
 * Describe:<br/>
 */
public class DiscoverFragment extends BaseFragment<LivelyPresenter> implements TabLayout.OnTabSelectedListener, ViewPager.OnPageChangeListener, View.OnClickListener {
    private NoSmoothViewPager mViewPager;
    //    private TabLayout mTabLayout;
    private List<String> mTabList = new ArrayList<>();
    private TabLayoutSubFragmentAdapter mAdapter;
    private List<Fragment> mFragments = new ArrayList<>();
    private ImageView mSearch;
    private MagicIndicator magicIndicator;
    private List<String> titleList = new ArrayList<>();
    private View viewStatus;

    @Override
    public int setLayoutResId() {
        return R.layout.fragment_discover;
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void initView() {
        viewStatus = mView.findViewById(R.id.view_status);
        StatusBarUtil.setPaddingSmart(mActivity, viewStatus);
        mViewPager = mView.findViewById(R.id.viewpager);
        magicIndicator = mView.findViewById(R.id.magicIndicator);
//        mTabLayout = mView.findViewById(R.id.tab_layout);
//        mSearch = mView.findViewById(R.id.ivSearch);
        initTabList();
        initIndicator();
        mAdapter = new TabLayoutSubFragmentAdapter(getChildFragmentManager(), getActivity(), mFragments, mTabList);
        mViewPager.setAdapter(mAdapter);
        mViewPager.setCurrentItem(0);
        mViewPager.setOffscreenPageLimit(0);
//        mTabLayout.setupWithViewPager(mViewPager);
//        mTabLayout.setTabMode(TabLayout.MODE_FIXED);
//        for (int i = 0; i < mTabLayout.getTabCount(); i++) {
//            mTabLayout.getTabAt(i).setCustomView(mAdapter.getTabView(i));
//        }
//        mTabLayout.addOnTabSelectedListener(this);
        mViewPager.addOnPageChangeListener(this);
//        mSearch.setOnClickListener(this);
    }

    private void initIndicator() {
        CommonNavigator commonNavigator = new CommonNavigator(mActivity);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return titleList.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, int index) {
                ScaleTransitionPagerTitleView titleView = new ScaleTransitionPagerTitleView(context);
                titleView.setText(titleList.get(index));
                titleView.setTextSize(18);
                titleView.setTypeface(Typeface.DEFAULT_BOLD);
                titleView.setMinScale(0.75f);
                titleView.setWidth(DisplayUtils.getScreenWidth(mActivity) / 5);
                titleView.setNormalColor(Color.parseColor("#7FFFFFFF"));
                titleView.setSelectedColor(Color.parseColor("#FFFFFF"));
                titleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mViewPager.setCurrentItem(index);
                    }
                });
                return titleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setMode(LinePagerIndicator.MODE_EXACTLY);
                indicator.setLineHeight(UIUtil.dip2px(context, 6));
                indicator.setLineWidth(UIUtil.dip2px(context, 10));
                indicator.setRoundRadius(UIUtil.dip2px(context, 3));
                indicator.setStartInterpolator(new AccelerateInterpolator());
                indicator.setEndInterpolator(new DecelerateInterpolator(2.0f));
                indicator.setColors(Color.parseColor("#FFFFFF"));
                return indicator;
            }
        });
        magicIndicator.setNavigator(commonNavigator);
        ViewPagerHelper.bind(magicIndicator, mViewPager);
    }

    private void initTabList() {
        mTabList.clear();
        mTabList.add(getString(R.string.title_discover));
        mTabList.add(getString(R.string.title_nearby));

        titleList.clear();
        titleList.add(getString(R.string.title_discover));
        titleList.add(getString(R.string.title_nearby));
//        mTabList.add(getString(R.string.title_newest));
        mFragments.clear();
        mFragments.add(new NewDiscoverFragment());
        mFragments.add(new NearbyFragment());
//        mFragments.add(new NewestFragment());
    }

    @Override
    public void initData() {

    }

    @Override
    public void initListener() {

    }

    @Override
    public void loadData() {

    }

    @Override
    public LivelyPresenter setPresenter() {
        return null;
    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        setTabSelectedState(tab);
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {
        setTabUnSelectedState(tab);
    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }

    private void setTabSelectedState(TabLayout.Tab tab) {
        View customView = tab.getCustomView();
        TextView tabText = (TextView) customView.findViewById(R.id.tv_tab_text);
        tabText.setTextColor(ContextCompat.getColor(mActivity, R.color.white));
        String s = tabText.getText().toString();
        tabText.setScaleX(1.5f);
        tabText.setScaleY(1.5f);
    }

    private void setTabUnSelectedState(TabLayout.Tab tab) {
        View customView = tab.getCustomView();
        TextView tabText = (TextView) customView.findViewById(R.id.tv_tab_text);
        tabText.setTextColor(ContextCompat.getColor(mActivity, R.color.white_alpha_50));
        String s = tabText.getText().toString();
        tabText.setScaleX(1f);
        tabText.setScaleY(1f);

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        printD("position=" + position + ",positionOffset=" + positionOffset + ",positionOffsetPixels=" + positionOffsetPixels);
    }

    @Override
    public void onPageSelected(int position) {
        printD("onPageSelected position=" + position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    public static void setTabWidth(final TabLayout tabLayout, final int padding) {
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                try {
                    //拿到tabLayout的mTabStrip属性
                    LinearLayout mTabStrip = (LinearLayout) tabLayout.getChildAt(0);

                    for (int i = 0; i < mTabStrip.getChildCount(); i++) {
                        View tabView = mTabStrip.getChildAt(i);

                        //拿到tabView的mTextView属性  tab的字数不固定一定用反射取mTextView
                        Field mTextViewField = tabView.getClass().getDeclaredField("mTextView");
                        mTextViewField.setAccessible(true);

                        TextView mTextView = (TextView) mTextViewField.get(tabView);

                        tabView.setPadding(0, 0, 0, 0);

                        //因为我想要的效果是   字多宽线就多宽，所以测量mTextView的宽度
                        int width = 0;
                        width = mTextView.getWidth();
                        if (width == 0) {
                            mTextView.measure(0, 0);
                            width = mTextView.getMeasuredWidth();
                        }

                        //设置tab左右间距 注意这里不能使用Padding 因为源码中线的宽度是根据 tabView的宽度来设置的
                        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
                        params.width = width;
                        params.leftMargin = padding;
                        params.rightMargin = padding;
                        tabView.setLayoutParams(params);

                        tabView.invalidate();
                    }

                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            case R.id.ivSearch:
//                startNewActivity(SearchActivity.class);
//                break;
        }
    }
}
